import Vue from 'vue'
import Router from 'vue-router'
import qs from 'qs'
import store from '@/../store'
import {
  detecteDevice
} from '../common/systeminfo'

// Routes Components
import systemRoute from './modules/system'
import tabbarRoute from './modules/tabbar'
import authorizeRoute from './modules/authorize'
import appRoute from './modules/app'
import activityRoute from './modules/activity'
import feedbackRoute from './modules/feedback'
import passportRoute from './modules/passport'
import shopRoute from './modules/shop'
import userRoute from './modules/user'
import memberRoute from './modules/member'
import pageRoute from './modules/page'
import tradeRoute from './modules/trade'
// import testRoute from './modules/test'
Vue.use(Router)

let routes = new Set([
  ...[{
    path: '/',
    name: '',
    redirect: '/home'
  }],
  ...tabbarRoute,
  ...authorizeRoute,
  ...appRoute,
  ...activityRoute,
  ...feedbackRoute,
  ...passportRoute,
  ...shopRoute,
  ...userRoute,
  ...memberRoute,
  ...pageRoute,
  ...systemRoute,
  ...tradeRoute,
  // ...testRoute,
  ...[
    // 404 page must be placed at the end !!!
    {
      path: '*',
      redirect: '/exception'
    }
  ]
])

// add route path
routes.forEach(route => {
  route.path = route.path || '/' + (route.name || '')
})

const router = new Router({
  mode: 'history', // 如果你是 history模式 需要配置 publicPath
  base: '/', // base: process.env.assetsRoot,
  routes: routes,
  scrollBehavior (to, from, savedPosition) {
    return {
      x: 0,
      y: 0
    }
  }
})

router.beforeEach((to, from, next) => {
  console.group('Router BeforeEach')
  console.log('[to]', to)
  console.log('[mode]', router.mode)
  // set document.title
  if (to.meta && to.meta.title) {
    document.title = to.meta.title
    console.log('[document.title]', document.title)
  }

  if (/\/passport\/login/g.test(to.path) && !/\/passport\//g.test(from.path) && sessionStorage.getItem('LoggedReferrer') === null) {
    console.log('[will to login]', from.path)
    // 储存来源路由
    sessionStorage.setItem('LoggedReferrer', from.path)
  }

  // 授权拦截
  if (!/authorize|share/g.test(to.path)) {
    // Unauthorized page authentication, access to basic information
    let isWechatBrowser = detecteDevice('wechat')
    // let wxUserInfo = sessionStorage.getItem('wxUserInfo')
    let wxUserInfo = store.state.authorize.connect
    console.log('[isWechatBrowser]', isWechatBrowser)
    console.log('[wxUserInfo]', wxUserInfo)
    // 如是微信浏览器并且未授权，开启微信授权校验
    if (!wxUserInfo && isWechatBrowser) {
      // 保存当前路由地址，授权后还会跳到此地址
      sessionStorage.setItem('wxRedirectUrl', to.fullPath)
      console.log('[wxRedirectUrl]', to.fullPath)

      // 请求微信授权,并跳转到 /authorize/wechat 路由
      let redirectUri = window.location.origin + (router.mode === 'hash' ? '/#/' : '/')
      let params = qs.stringify({
        appid: process.env.WECHAT_APP_ID,
        redirect_uri: redirectUri + 'authorize/wechat',
        response_type: 'code',
        scope: 'snsapi_userinfo',
        state: 'STATE'
      })
      console.log('[params]', params)
      let redirectUrl = `${process.env.WECHAT_OAUTH_URL}?${params}#wechat_redirect`
      console.log('[location.href]', redirectUrl)
      window.location.href = redirectUrl
      return false
    } else {
      // Authorized or non wechat browser release
      console.log('[next normal path]', to.path)
      next()
    }
  } else {
    // Release all authorization pages
    console.log('[next auth]', to.path)
    next()
  }
  console.groupEnd('Router BeforeEach')
})

// wx 用的是vux中的WechatPlugin
// const jsApiList = ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareQZone', 'hideMenuItems']
// router.afterEach((to) => {
//   if (!sessionStorage.getItem('initLink')) {
//     sessionStorage.setItem('initLink', document.URL)
//   }
//   let _url = window.location.origin + to.fullPath
//   // 非ios设备，切换路由时候进行重新签名
//   if (window.__wxjs_is_wkwebview !== true) {
//     setTimeout(() => {
//       http.get('/api/wechat/getSign?url=' + encodeURIComponent(_url)).then(res => {
//         let signInfo = res.data.sign
//         signInfo.jsApiList = jsApiList
//         wx.config(signInfo)
//       })
//     }, 400)
//   }
//   // ios 设备进入页面则进行js-sdk签名
//   if (window.__wxjs_is_wkwebview === true) {
//     let _url = window.location.href.split('#')[0]
//     setTimeout(() => {
//       http.get('/api/wechat/getSign?url=' + encodeURIComponent(sessionStorage.getItem('initLink'))).then(function (res) {
//         let signInfo = res.data.sign
//         signInfo.jsApiList = jsApiList
//         wx.config(signInfo)
//       })
//     }, 400)
//   }
// })

export default router
